package handler

import (
	"github.com/gin-gonic/gin"
	"shopcar/api/request"
	"shopcar/internal/dao"
	"shopcar/internal/model"
)

func LikeAdd(c *gin.Context) {
	var req request.LikeAdd
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  err.Error(),
			"data": err.Error(),
		})
		return
	}
	var like model.Like
	dao.GetOneByFields(&model.Like{ShopId: int(req.ShopId)}, &like)
	if like.Id != 0 {
		c.JSON(200, gin.H{
			"code": 10000,
			"msg":  "当前商品已被收藏",
			"data": nil,
		})
		return
	}
	result := dao.Create(&model.Like{
		UserId: c.GetInt("UserId"),
		ShopId: int(req.ShopId),
	})
	if !result {
		c.JSON(200, gin.H{
			"code": 10000,
			"msg":  "收藏失败",
			"data": nil,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "收藏成功",
		"data": nil,
	})
}

func LikeRemove(c *gin.Context) {
	var req request.LikeRemove
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code": 10000,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	var like model.Like
	dao.GetOneByFields(&model.Like{Id: uint(req.Id)}, &like)
	if like.Id == 0 {
		c.JSON(200, gin.H{
			"code": 10000,
			"msg":  "当前收藏信息不存在",
			"data": nil,
		})
		return
	}
	result := dao.Delete(&model.Like{Id: uint(req.Id)})
	if !result {
		c.JSON(200, gin.H{
			"code": 10000,
			"msg":  "取消收藏失败",
			"data": nil,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "取消收藏成功",
		"data": nil,
	})
}

func LikeSearch(c *gin.Context) {
	var req request.LikeSearch
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code": 10000,
			"msg":  err.Error(),
			"data": nil,
		})
		return
	}
	var like []model.Like
	result := dao.GetListByFields(&model.Like{UserId: int(req.UserId)}, &like)
	if !result {
		c.JSON(200, gin.H{
			"code": 10000,
			"msg":  "查询失败",
			"data": nil,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": like,
	})
}
